
<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin: 15px 0;
  }

  .hjd-drawer__footer {
    margin-top: 50px;
  }
}
</style>

<template>
  <el-drawer
    ref="drawer"
    custom-class="hjd-drawer"
    title="分配菜单"
    :visible.sync="showDialog"
    :wrapper-closable="true"
    @close="$emit('update:visible', false)"
  >
    <div class="hjd-drawer__content">
      <el-form ref="dataForm" :model="form" label-width="0px" style=" margin-left:20px;">
        <div class="hjd-drawer__content_tree">
          <el-form-item label>
            <el-tree
              ref="tree"
              :data="treeData"
              show-checkbox
              node-key="menu_id"
              :props="defaultProps"
              lazy
              :load="load"
              default-expand-all
            />
          </el-form-item>
        </div>
        <div class="hjd-drawer__footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>

import _ from 'lodash'
import { handleList } from '@/api/system/auth/menu'
import { handleRole } from '@/api/system/auth/role'

export default {
  name: 'RoleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: 'new'
    },
    data: {
      type: Object,
      default: () => ({})
    },

    parent: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showDialog: this.visible,
      beforeData: {},
      treeData: [],
      defaultProps: {
        label: 'menu_name'
      },
      /**
       * 表单内容
       */
      form: {
        role_id: '',
        name: '',
        menu: []
      }
    }
  },

  created() {
    this.beforeData = _.cloneDeep(this.data.menu)
    Object.keys(this.form).forEach((key) => {
      this.form[key] = this.data[key]
    })
  },

  methods: {

    load(node, resolve) {
      if (!_.get(node, 'data.hasChildren', true)) {
        const tree = _.get(this.$refs, 'tree')
        if (tree) tree.setCheckedKeys(this.form.menu)

        resolve([])
        return
      }

      handleList({
        menu_pid: node.data.menu_id,
        page: 1,
        limit: 10000
      }).then(response => {
        // _.forEach(response.data.data, item => {
        //   item.menu_name = `${item.menu_name} - ${item.menu_id}`
        // })

        resolve(response.data.data)
      })
    },

    submit() {
      this.form.menu = this.$refs.tree.getCheckedKeys()
      // 数据没改动 直接关闭弹窗
      if (_.isEqual(this.form.menu, this.beforeData)) {
        this.showDialog = false
        return
      }
      const queryData = this.form

      handleRole(queryData).then((res) => {
        this.showDialog = false
        this.$notify.success(res.msg)
        this.$emit('reload')
      })
    }
  }
}
</script>
